package com.example.wm.controller;


import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wm.OV.*;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;

import com.example.wm.entity.*;
import com.example.wm.mapper.TenderEntityMapper;
import com.example.wm.service.*;
import com.example.wm.utils.TsyUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController

@RequestMapping("/TenderEntity")
//总结
public class TenderEntityContoller  {
    @Resource
    private TenderEntityService tenderEntityService;
    @Resource
    private TenderEntityMapper tenderEntityMapper;
    @Resource
    private TenderDetailService tenderDetailService;
    @Resource
    private TenderTagsService tenderTagsService;
    @Resource
    private TsyUtils tsyUtils;
    @Resource
    private ProductLibraryService productLibraryService;
    @Resource
    private ProductunpackingService productunpackingService;
    @PostMapping("/save")
    public Result save(@RequestBody TenderEntityVo tenderEntityVo) {
        tenderEntityVo.getTenderEntity().setInserttime(tsyUtils.getnowtime());
        Boolean a=  tenderEntityService.save(tenderEntityVo.getTenderEntity());
//            for(TenderDetails td: tenderEntityVo.getTenderDetailsList()){
//                td.setTdid(tenderEntityVo.getTenderEntity().getId());
//                tenderDetailService.save(td);
//            }
        return ResultData.success(a);
    }
    @PostMapping("/delete")
    public Result delete(@RequestBody TenderEntity tenderEntity) {
          LambdaQueryWrapper<TenderDetails> lq=new LambdaQueryWrapper<>();
          lq.eq(TenderDetails::getTdid,tenderEntity.getId());
          List<TenderDetails> list=tenderDetailService.list(lq);
          for(TenderDetails tender:list){
              LambdaQueryWrapper<Productunpacking> lqp=new LambdaQueryWrapper<>();
              lqp.eq(Productunpacking::getTenderdetailid,tender.getId());
              List<Productunpacking> productunpackingList=new ArrayList<>();
              productunpackingService.removeBatchByIds(productunpackingList);
              tenderDetailService.removeById(tender);
          }
        return ResultData.success(list);
    }
    @PostMapping("/deletedetails")
    public Result deletedetails(@RequestBody TenderDetails tenderDetails) {

        LambdaQueryWrapper<Productunpacking> lq=new LambdaQueryWrapper<>();
        lq.eq(Productunpacking::getTenderdetailid,tenderDetails.getId());
        List<Productunpacking> list=productunpackingService.list(lq);

        Boolean b=null;
        if(!list.isEmpty()){

            productunpackingService.removeBatchByIds(list);
            b=  tenderDetailService.removeById(tenderDetails.getId());
        }
        return ResultData.success(b);
    }


    @PostMapping("/updatetender")
    public Result updatetender(@RequestBody TenderEntity tender) {
        tender.setInserttime(tsyUtils.getnowtime());
      Boolean a=  tenderEntityService.updateById(tender);
        return ResultData.success(a);
    }
    @PostMapping("/updatetenderdt")
    public Result updatetenderdt(@RequestBody TenderDetails tenderDetails) {
        Boolean a=  tenderDetailService.updateById(tenderDetails);
        return ResultData.success(a);
    }
    @PostMapping("/savedetails")
    public Result savedetails(@RequestBody TenderDetails tenderDetails) {
        Boolean a=  tenderDetailService.save(tenderDetails);
        return ResultData.success(a);
    }
    @PostMapping("/savetagBatch")
    public Result savetagBatch(@RequestBody List<TenderTags> tenderTags) {
        for (TenderTags te:tenderTags){
            te.setInserttime(tsyUtils.getnowtime());
        }
        Boolean a=  tenderTagsService.saveBatch(tenderTags);
        return ResultData.success(a);
    }
    @PostMapping("/savetag")
    public Result savetag(@RequestBody TenderTags tenderTags) {

        tenderTags.setInserttime(tsyUtils.getnowtime());

        Boolean a=  tenderTagsService.save(tenderTags);
        return ResultData.success(a);
    }
    @PostMapping("/inserttenderBatch")
    public Result inserttender(@RequestBody List<TenderEntity> tenderEntity) {
        for (TenderEntity te:tenderEntity){
            te.setInserttime(tsyUtils.getnowtime());
        }
        Boolean a=  tenderEntityService.saveBatch(tenderEntity);
        return ResultData.success(a);
    }
    @PostMapping("/inserttendetailsBatch")
    public Result inserttendetailsBatch(@RequestBody List<TenderDetails> tenderDetailsList) {
        for (TenderDetails te:tenderDetailsList){
            te.setInsertime(tsyUtils.getnowtime());
        }
        Boolean a=  tenderDetailService.saveBatch(tenderDetailsList);
        return ResultData.success(a);
    }
    @PostMapping("/inserttender")
    public Result inserttender(@RequestBody TenderEntity tenderEntity) {
        tenderEntity.setInserttime(tsyUtils.getnowtime());
        Boolean a=  tenderEntityService.save(tenderEntity);
        return ResultData.success(a);
    }

    @PostMapping("/insertdetail")
    @Transactional
    public Result insertdetail(@RequestBody JSONObject jsonObject) {
        try {
            // 1. 参数提取与验证
            String name = jsonObject.getString("name");
            String type = jsonObject.getString("type");
            if (StringUtils.isBlank(name) || StringUtils.isBlank(type)) {
                return ResultData.error(403,"名称和类型不能为空");
            }

            // 2. 创建TenderDetails对象
            TenderDetails tenderDetails = new TenderDetails();
            tenderDetails.setNametd(jsonObject.getString("nametd"));
            tenderDetails.setNumber(jsonObject.getString("number"));
            tenderDetails.setHeavey(jsonObject.getString("heavey"));

            // 3. 查询是否存在匹配的TenderEntity
            LambdaQueryWrapper<TenderEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TenderEntity::getName, name)
                    .eq(TenderEntity::getType, type);

            TenderEntity tenderEntity = tenderEntityService.getOne(queryWrapper);
//            List<TenderEntity> list= tenderEntityService.list(queryWrapper);
//            TenderEntity existingEntity=list.get(0);
            // 4. 处理不同情况
            if (tenderEntity != null) {
                // 情况1: 存在完全匹配的记录
                tenderDetails.setTdid(tenderEntity.getId());
            } else {
                // 情况2: 不存在完全匹配的记录
                tenderEntity = handleNonExactMatch(name, type);
                tenderDetails.setTdid(tenderEntity.getId());
            }

            // 5. 保存详情
            boolean saved = tenderDetailService.save(tenderDetails);
            return ResultData.success(saved);
        } catch (Exception e) {
            log.error("保存招标详情失败", e);
            return ResultData.error(403,"保存招标详情失败: " + e.getMessage());
        }
    }

    private TenderEntity handleNonExactMatch(String name, String type) {
        // 查询同名但类型不同的记录
        LambdaQueryWrapper<TenderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TenderEntity::getName, name);

       List<TenderEntity> list= tenderEntityService.list(queryWrapper);
        TenderEntity existingEntity=list.get(list.size()-1);
        if (existingEntity == null) {
            // 情况2a: 完全不存在同名记录，创建新记录
            return createNewTenderEntity(name, type);
        } else if (StringUtils.isBlank(existingEntity.getType())) {
            // 情况2b: 存在同名记录但类型为空，更新类型
            existingEntity.setType(type);
            tenderEntityService.updateById(existingEntity);
            return existingEntity;
        } else {
            // 情况2c: 存在同名但不同类型记录，创建新记录
            return createNewTenderEntity(name, type);
        }
    }

    private TenderEntity createNewTenderEntity(String name, String type) {
        TenderEntity newEntity = new TenderEntity();
        newEntity.setName(name);
        newEntity.setType(type);
        newEntity.setInserttime(tsyUtils.getnowtime());
        tenderEntityService.save(newEntity);
        return newEntity;
    }
    @PostMapping("/findtage")
    public Result findtage() {
     List<TenderTags>  list=tenderTagsService.list();
     return ResultData.success(list);
    }



    @PostMapping("/findtype")
    public Result findtype() {

        LambdaQueryWrapper<TenderEntity> lq=new LambdaQueryWrapper<>();
        List<TenderEntity> list=tenderEntityMapper.selectList(lq);
        HashSet resultMap = new HashSet();

        for (TenderEntity td : list) {
           resultMap.add(td.getType());
        }
        return ResultData.success(resultMap);
    }
    @PostMapping("/findbyid")
    public Result findbyid(@RequestBody TenderDetails tenderDetails) {

        LambdaQueryWrapper<TenderDetails> lq=new LambdaQueryWrapper<>();
        lq.eq(TenderDetails::getId,tenderDetails.getId());
        TenderDetails tenderDetails1=tenderDetailService.getOne(lq);

        return ResultData.success(tenderDetails1);
    }
    @PostMapping("/findAll")
    public Result findAll(@RequestBody JSONObject jsonObject ) {
         String type=jsonObject.getString("type");
        LambdaQueryWrapper<TenderEntity> lq=new LambdaQueryWrapper<>();

        if(!Objects.equals(type, "全部")){
            lq.eq(TenderEntity::getType,type);

        }

        lq.orderByDesc(TenderEntity::getInserttime);
//        List<TenderEntity> list=tenderEntityMapper.selectList(lq);
        Page<TenderEntity> pageInfo = new Page<>(jsonObject.getLong("page"),jsonObject.getLong("pageSize"));
        Page<TenderEntity>  list3=tenderEntityService.page(pageInfo,lq);
//        System.out.println("list3"+list3);
        TenderEntityPageDetail tenderEntityPageDetail=new TenderEntityPageDetail();

        List<TenderEntityPageVo> tenderEntityPageVoList=new ArrayList<>();
        for (TenderEntity td : list3.getRecords()) {
            LambdaQueryWrapper<TenderDetails> lqd=new LambdaQueryWrapper<>();
            lqd.eq(TenderDetails::getTdid,td.getId());
            List<TenderDetails> tenderList=tenderDetailService.list(lqd);
            List<TenderDetails> list1=new ArrayList<>();
            list1.addAll(tenderList);
            TenderEntityPageVo tenderEntityPageVo=new TenderEntityPageVo();
            tenderEntityPageVo.setTenderDetailsList(list1);
            tenderEntityPageVo.setId(td.getId());
            tenderEntityPageVo.setName(td.getName());
            tenderEntityPageVo.setMoneys(td.getMoneys());
            tenderEntityPageVo.setType(td.getType());
            tenderEntityPageVo.setInserttime(td.getInserttime());
            tenderEntityPageVo.setStatue(td.getStatue());
            tenderEntityPageVo.setTendergoods(td.getTendergoods());
            tenderEntityPageVoList.add(tenderEntityPageVo);
//            tenderEntityPageDetail.setTenderEntityPageVo(tenderEntityPageVo);

        }

       tenderEntityPageDetail.setTenderEntityPageVoList(tenderEntityPageVoList);
        tenderEntityPageDetail.setCurrent(list3.getCurrent());
        tenderEntityPageDetail.setPages(list3.getPages());
        tenderEntityPageDetail.setTotal(list3.getTotal());
        return ResultData.success(tenderEntityPageDetail);
    }
     //根据id获取明细
     @PostMapping("/finddetialbyid")
     public Result finddetialbyid(@RequestBody TenderEntity tenderEntity) {
         List<TenderDetandPro> tenderDetandPros = new ArrayList<>();
         LambdaQueryWrapper<TenderDetails> lqd = new LambdaQueryWrapper<>();
         lqd.eq(TenderDetails::getTdid, tenderEntity.getId());
         List<TenderDetails> tenderList = tenderDetailService.list(lqd);

         if (!tenderList.isEmpty()) {
             for (TenderDetails tenderDetails : tenderList) {
                 TenderDetandPro tenderDetandPro = new TenderDetandPro();

                 // 1. 先拷贝通用属性
                 BeanUtils.copyProperties(tenderDetails, tenderDetandPro);

                 // 2. 再设置需要计算的特殊属性
                 LambdaQueryWrapper<Productunpacking> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                 lambdaQueryWrapper.eq(Productunpacking::getTenderdetailid, tenderDetails.getId());
                 Long n = productunpackingService.count(lambdaQueryWrapper);
                 tenderDetandPro.setProductingnumber(Math.toIntExact(n));
//                 if(n>0 && !Objects.equals(tenderDetandPro.getStatusprodect(), "拆解完")){
//                     tenderDetandPro.setStatusprodect("拆解中");
//                 }else if(n>0 && Objects.equals(tenderDetandPro.getStatusprodect(), "拆解完")){
//                     tenderDetandPro.setStatusprodect("拆解完");
//                 }else {
//                     tenderDetandPro.setStatusprodect("未拆解");
//
//                 }
                 // 3. 将新对象加入结果列表
                 tenderDetandPros.add(tenderDetandPro);
             }
         }

         // 4. 返回处理好的新列表
         return ResultData.success(tenderDetandPros);
     }
    @PostMapping("/findAll2")
    public Result findAll2(@RequestBody JSONObject jsonObject ) {
//        String type=jsonObject.getString("type");
        LambdaQueryWrapper<TenderEntity> lq=new LambdaQueryWrapper<>();
        lq.orderByDesc(TenderEntity::getInserttime);
//        lq.eq(TenderEntity::getType,type);
//        List<TenderEntity> list=tenderEntityMapper.selectList(lq);
        Page<TenderEntity> pageInfo = new Page<>(jsonObject.getLong("page"),jsonObject.getLong("pageSize"));
        Page<TenderEntity>  list3=tenderEntityService.page(pageInfo,lq);
        System.out.println("list3"+list3);

        List<TenderDetails> list1=new ArrayList<>();
        for (TenderEntity td : list3.getRecords()) {
            LambdaQueryWrapper<TenderDetails> lqd=new LambdaQueryWrapper<>();
            lqd.eq(TenderDetails::getTdid,td.getId());
            List<TenderDetails> tenderList=tenderDetailService.list(lqd);
            list1.addAll(tenderList);

        }
        TenderEntityPageDetail tenderEntityPageDetail=new TenderEntityPageDetail();
        tenderEntityPageDetail.setCurrent(list3.getCurrent());
        tenderEntityPageDetail.setTotal(list3.getTotal());
        return ResultData.success(tenderEntityPageDetail);
    }
    @PostMapping("/chatAi")
    public Result chatAi(@RequestBody JSONObject jsonObject) {
        String result = null;
        try {

            String baseUrl = "https://api.coze.cn/v1/workflow/run";

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("input", jsonObject.getString("input"));  // 自动转换为JSON对象
            Map<String, Object> requestParam = new HashMap<>();
            requestParam.put("workflow_id", "7492353657854722048");
            requestParam.put("parameters", parameters);  // 使用Map对象而非字符串


            String jsonStr = JSONUtil.toJsonStr(requestParam);
            HttpResponse response = HttpRequest.post(baseUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    // 发送json数据需要设置contentType
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.AUTHORIZATION,"Bearer pat_SwsgPNa4pANZpMemfCObTJW8eyix8gdXYVTtzwCDlXclgsryUdDFlZJBNZkEfoIY")
                    .body(jsonStr)
                    .execute();
            if (response.getStatus() == HttpStatus.HTTP_OK) {
                result = response.body();
                // 将获取到的手机号信息解析为 JSON 对象
                JSONObject jsons = JSONObject.parseObject(result);

//                String phoneNumber = jsons.getJSONObject("phone_info").getString("phoneNumber");
       return ResultData.success(jsons);


            }
        } catch (Exception e) {
            e.printStackTrace();


        }
        return ResultData.success();

    }

    @Transactional
    @PostMapping("/readerxlsx")
    public Result inserttmgxid( @RequestBody MultipartFile file) throws IOException {
        // 获取拥有后缀的文件名 「abc.csv」
        String fileName = file.getOriginalFilename(); // 获取文件名
        // 获取后缀 「abc」
        String csvFile = fileName.substring( fileName.indexOf(".")+1);
        System.out.println(csvFile+":cvFilname");
        System.out.println(fileName+"fileNamefileNamefileNamefileName");
        InputStream is = null;
        if(csvFile.equals("xlsx") ||csvFile.equals("xls") ){
            try{

                is = file.getInputStream();
                List<Map> confedrateStaticList = tenderEntityService.getListByExcel(is,fileName);// 获取解析后的List集合

                System.out.println(confedrateStaticList.toString());
//            Boolean result = confedrateStaticService.batchImportStuInfo(studentList); // 把数据插入数据库
//            if (result){
//                return Msg.sussess().add("info", "文件上传成功！");
//            }else {
//                return Msg.failure().add("info", "文件上传失败！");
//            }
                return ResultData.success(confedrateStaticList);
            }catch (Exception e){
                e.printStackTrace();
            } finally {
                is.close();
            }

        }
        else{
            //  获取 csv 数据

            List<Map> l=   tsyUtils.submitOriginalFile(file);
            return ResultData.success(l);

        }

        return ResultData.success("304", "文件错误！");



    }
    //拆解预估值
    @PostMapping("/getsummery")
    public Result getsummery(@RequestBody TenderEntity tender) {
        LambdaQueryWrapper<TenderDetails> lq = new LambdaQueryWrapper<>();
        lq.eq(TenderDetails::getTdid, tender.getId());
        List<TenderDetails> tenderDetailsList = tenderDetailService.list(lq);
        ArrayList<Productunpacking> arrayList = new ArrayList<>();
        if (!tenderDetailsList.isEmpty()) {
            for (TenderDetails tenderDetails : tenderDetailsList) {
                LambdaQueryWrapper<Productunpacking> lq2 = new LambdaQueryWrapper<>();
                lq2.eq(Productunpacking::getTenderdetailid, tenderDetails.getId());
                List<Productunpacking> productunpackingList = productunpackingService.list(lq2);
                arrayList.addAll(productunpackingList);
            }
        }

        return ResultData.success(arrayList);
    }
    //模糊查询产品
    @PostMapping("/findproduction")
    public Result findproduction(@RequestBody ProductLibrary productLibrary) {
        LambdaQueryWrapper<ProductLibrary> lq = new LambdaQueryWrapper<>();

        lq.like(ProductLibrary::getProname, productLibrary.getProname());


        List<ProductLibrary> list = productLibraryService.list(lq);
        return ResultData.success(list);
    }
}
